package org.elec.mac.utils;

import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.elec.mac.entity.OAuthToken;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Bean on 2017/5/10.
 */
@Slf4j
public class Utils {

    /**
     * ETFFSL金额默认值
     */
    public static final double ETFFSL_DEFAULT_DOUBLE = 0.0000;

    /**
     * 金额保留四位
     *
     * @param money 金额
     * @return 返回
     */
    public static double convertDouble(Double money) {
        if(null == money) {
            return ETFFSL_DEFAULT_DOUBLE;
        }
        return Math.round(money * 10000) / 10000.0;
    }

    /**
     * 获取保留小数位的数字
     *
     * @param value
     * @param precision
     * @return
     */
    public static double getPrecisionDouble(double value, int precision) {
        BigDecimal bg = new BigDecimal(value);
        double f1 = bg.setScale(precision, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1;
    }

    /**
     * 格式化double类型值，使得其末尾保留两位小数
     *
     * @param value
     * @return
     */
    public static String formatDouble(double value) {
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(value);
    }

    /**
     * 将字符串数字转化为int型数字
     *
     * @param str      被转化字符串
     * @param defValue 转化失败后的默认值
     * @return int
     */
    public static int parseInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch(Exception e) {
            return defValue;
        }
    }

    /**
     * 将字符串数字转化为long型数字
     *
     * @param str      被转化字符串
     * @param defValue 转化失败后的默认值
     * @return long
     */
    public static long parseLong(String str, long defValue) {
        try {
            return Long.parseLong(str);
        } catch(Exception e) {
            return defValue;
        }
    }

    /**
     * 将字符串数字转化为BigDecimal型数字
     *
     * @param str      被转化字符串
     * @param defValue 转化失败后的默认值
     * @return BigDecimal
     */
    public static BigDecimal parseBigDecimal(String str, BigDecimal defValue) {
        try {
            return new BigDecimal(str);
        } catch(Exception e) {
            return defValue;
        }
    }

    /**
     * 将字符串数字转化为double型数字
     *
     * @param str      被转化字符串
     * @param defValue 转化失败后的默认值
     * @return double
     */
    public static double parseDouble(String str, double defValue) {
        try {
            return Double.parseDouble(str);
        } catch(Exception e) {
            return defValue;
        }
    }

    /**
     * 将字符串数字转化为boolean型数字
     *
     * @param str      被转化字符串
     * @param defValue 转化失败后的默认值
     * @return boolean
     */
    public static boolean parseBoolean(String str, boolean defValue) {
        try {
            return Boolean.parseBoolean(str);
        } catch(Exception e) {
            return defValue;
        }
    }

    /**
     * @param obj
     * @return
     */
    public static String obj2String(Object obj) {
        if(obj != null) {
            return (String) obj;
        }
        return "";
    }

    /**
     * EMAIL验证
     *
     * @param str
     * @return
     */
    public static boolean isMail(String str) {
        String check = "^([a-z0-9A-Z]+[-|\\._]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(str);
        boolean isMatched = matcher.matches();
        if(isMatched) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 验证手机号
     *
     * @param telno
     * @return
     */
    public static boolean isTelNo(String telno) {
        String expression = "(^13\\d{9}$|^15[8-9]{1}\\d{8}$)";
        return (Utils.isValidate(telno, expression));
    }

    /**
     * 数字字母混合
     *
     * @param str
     * @return
     */
    public static boolean isAlphanumeric(String str) {
        String expression = "/^[a-zA-Z0-9]+$/i";
        return (Utils.isValidate(str, expression));
    }

    /**
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        String expression = "/^[0-9]+$/i";
        return (Utils.isValidate(str, expression));
    }

    /**
     * @param str
     * @return
     */
    public static boolean isPhone(String str) {
        String expression = "/^\\+?([0-9]|[-|' '])+$/i";
        return (Utils.isValidate(str, expression));
    }


    /**
     * 验证正则表达式
     *
     * @param value
     * @param expression
     * @return
     */
    public static boolean isValidate(String value, String expression) {

        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(value);

        return matcher.find();
    }

    /**
     * @param value
     * @return
     */
    public static int getIntValue(Integer value) {
        if(value == null) {
            return 0;
        } else {
            return value.intValue();
        }
    }

    /**
     * @param value
     * @return
     */
    public static long getLongValue(Long value) {
        if(value == null) {
            return 0;
        } else {
            return value.longValue();
        }
    }

    /**
     * @param value
     * @param def
     * @return
     */
    public static String intergerToString(Integer value, String def) {
        if(value == null) {
            return def;
        } else {
            return value.toString();
        }
    }

    /**
     * @param value
     * @param def
     * @return
     */
    public static String longToString(Long value, String def) {
        if(value == null) {
            return def;
        } else {
            return value.toString();
        }
    }

    public static String signSha1(Map<String, String> data) {
        Set keySet = data.keySet();
        String[] keyArray = (String[]) keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        String[] var6 = keyArray;
        int var7 = keyArray.length;

        for(int var8 = 0; var8 < var7; ++var8) {
            String k = var6[var8];
            if(!k.equals("sign") && ((String) data.get(k)).trim().length() > 0) {
                if(var8 < var7 - 1){
                    sb.append(k).append("=").append(((String) data.get(k)).trim()).append("&");
                }else {
                    sb.append(k).append("=").append(((String) data.get(k)).trim());
                }
            }
        }
        log.debug("[sb] = " + sb.toString());
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(sb.toString().getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for(byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static Map<String, String> wxConfigMap(String openid, EhCacheCacheManager manager, String url){
        Cache authTokenCache = manager.getCache("authTokenCache");

        OAuthToken authToken = authTokenCache.get(openid, OAuthToken.class);

        Map<String, String> mapSign = new HashMap<>();
        String noncestr = WXPayUtil.generateNonceStr();
        String timestamp = String.valueOf(System.currentTimeMillis());
        timestamp = timestamp.substring(0, timestamp.length() - 3);
        String jsapi_ticket = authToken.getTicket();

        mapSign.put("noncestr", noncestr);
        mapSign.put("timestamp", timestamp);
        mapSign.put("url", url);
        mapSign.put("jsapi_ticket", jsapi_ticket);

        String sign = signSha1(mapSign);
        mapSign.put("sign",sign);

        return mapSign;
    }
}
